package com.qf.web.sys_user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.web.sys_menu.entity.Menu;
import com.qf.web.sys_menu.entity.MenuTree;
import com.qf.web.sys_menu.servie.MenuService;
import com.qf.web.sys_user.entity.AssignParams;
import com.qf.web.sys_user.entity.AssignVo;
import com.qf.web.sys_user.entity.PagePram;
import com.qf.web.sys_user.entity.User;
import com.qf.web.sys_user.mapper.UserMapper;
import com.qf.web.sys_user.service.UserService;
import com.qf.web.sys_user_role.entity.UserRole;
import com.qf.web.sys_user_role.service.UserRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author xufuhan
 * @Date 2024/9/10 11:32
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public IPage<User> list(PagePram pram) {
        //构造分页对象
        IPage<User> page=new Page<>();
        page.setCurrent(pram.getCurrentPage());
        page.setSize(pram.getPageSize());
        //构造查询条件
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        if (StringUtils.isNotEmpty(pram.getNickName())){
            wrapper.lambda().like(User::getNickName,pram.getNickName());
        }
        if (StringUtils.isNotEmpty(pram.getPhone())){
            wrapper.lambda().like(User::getPhone,pram.getPhone());
        }
        return this.baseMapper.selectPage(page,wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(User user) {
        //新增用户
        int insert = this.baseMapper.insert(user);
        //保存劫色
        if (insert>0){
            UserRole userRole = new UserRole();
            userRole.setRoleId(userRole.getRoleId());
            userRole.setUserId(user.getUserId());
            userRoleService.save(userRole);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editUser(User user) {
        //编辑
        int update = this.baseMapper.updateById(user);
        if (update>0){
            //先删除旧数据
            QueryWrapper<UserRole> wrapper=new QueryWrapper<>();
            wrapper.lambda().eq(UserRole::getUserId,user.getUserId());
            userRoleService.remove(wrapper);

            //，在插入新数据
            UserRole userRole = new UserRole();
            userRole.setRoleId(user.getRoleId());
            userRole.setUserId(user.getUserId());
            userRoleService.save(userRole);
        }
    }


}
